var audio = null;
var audioEndCallback = null;

function initBg(){
    
    audio = document.createElement('audio');
    audio.setAttribute("rel", "noreferrer");
    
    audio.addEventListener('error', function(e){
        console.log(e,this);
        //todo
    }, false);
    
    setIcon();
    chrome.browserAction.setTitle({
        title:'Toggle On/Off'
    });
    chrome.browserAction.onClicked.addListener(function(tab) {
        toggleActive();
        //
        // remove content scripts...
        //
    });
}

function toggleActive(){
    if( isActive() ){
        localStorage.setItem("active",false);
        audio.pause();
        audioEndCallback = null;
    } else {
        localStorage.setItem("active",true);
    }
    setIcon();
}

function setIcon(){
    var active = isActive();
    var icon = 'img/icon32.png';
    if( !active ){
        icon = 'img/icon32_off.png';
    }
    chrome.browserAction.setIcon({
        path:icon
    });
}

function isActive(){
    var active = localStorage.getItem("active");
    if( active === null ){
        active = true;
        localStorage.setItem("active",true);
    }
    if( active == "true" ){
        active = true;
    } else {
        active = false;
    }
    return active;
}

chrome.extension.onConnect.addListener(function(port) {
    console.assert(port.name == "audio");
    
    port.onMessage.addListener(function(data) {
        switch( data.payload ){
            case 'stop':
                if( audioEndCallback != null ){
                    audio.removeEventListener('ended', audioEndCallback, false);
                    audioEndCallback = null;
                }
                audio.pause();
            break;
            case 'play':
                if(audioEndCallback)
                    audio.removeEventListener('ended', audioEndCallback, false);
                audioEndCallback = function(){
                    port.postMessage({audio: "end"});
                };
                audio.src = data.url;
                audio.addEventListener('ended', audioEndCallback, false);
                audio.addEventListener('pause', audioEndCallback, false);
                audio.play();
            break;
            default:
            break;
        }
    });
    
});

chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
    if (request.message == "isactive"){
        sendResponse({
            active: isActive()
            });
    } else if (request.message == "parse"){
        var img = new Image();
        img.onload = function() {
            var canvas = Pixastic.process(img,"brightness", {brightness:0,contrast:1.5});
            sendResponse({data: canvas.toDataURL()});
        };
        img.src = request.img;
    } else {
        sendResponse({}); // snub them.
    }
});
